package com.alpha.servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.alpha.bom.Exam;
import com.alpha.bom.ExamResponse;
import com.alpha.bom.Professor;
import com.alpha.bom.Question;
import com.alpha.bom.RealExam;
import com.alpha.bom.Student;
import com.alpha.dao.AnswerDao;
import com.alpha.dao.ExamDao;
import com.alpha.dao.ExamResponseDao;
import com.alpha.dao.QuestionDao;

/**
 * Servlet implementation class ReviewExamServlet
 */
@WebServlet("/ReviewExamServlet")
public class ReviewExamServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(ReviewExamServlet.class.getName());

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ReviewExamServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		logger.info(this.getClass().getSimpleName()+" get method started.");
		
		Student student = null;
		ExamResponse examResponse = null;
		
		HttpSession session = request.getSession();
		
		//Do not allow a professor to access this
		if(session.getAttribute("user")!=null && (session.getAttribute("user") instanceof Professor)){
			response.sendRedirect("403.jsp");
			return;
		}
		
		if(session.getAttribute("user")!=null && (session.getAttribute("user") instanceof Student)){
			student = (Student) session.getAttribute("user");
		}
		
		//get examresponse object from session
		if(session.getAttribute("exam_response")!=null){
			examResponse = (ExamResponse) session.getAttribute("exam_response");
		} else {
			if(student!=null){
				response.sendRedirect("MyExamServlet?error=Session+time+out.");
				return;
			} else {
				response.sendRedirect("PracticeExamsServlet?error=Session+time+out.");	
				return;
			}
		}
		
		//end the exam if exam is already deactivated by the professor
		ExamDao eDao = new ExamDao();
		Exam tempExam;
		try {
			tempExam = eDao.retrieveExamById(examResponse.getExam().getExamId());
			if("Real".equals(tempExam.getExamType()) && student!=null){
				if(((RealExam)tempExam).isLocked()){
					ExamResponseDao erDao = new ExamResponseDao();
					try {
						erDao.updateDateTaken(examResponse.getExam().getExamId(), student.getUserId(), new Date());
					} catch (NamingException e) {
						logger.error(e.getMessage());
						return;
					} catch (SQLException e) {
						logger.error(e.getMessage());
						return;
					}
					examResponse.setComplete(true);	
					session.removeAttribute("exam_response");
					request.setAttribute("exam_response", examResponse);
					RequestDispatcher dispatcher = request.getRequestDispatcher("StudentResponse.jsp?error=Sorry,+the+exam+is+already+deactivated.");
					dispatcher.forward(request, response);
					return;
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			return;
		}
		
		if(request.getParameter("q_index") != null && request.getParameter("id") != null) {
			try {
				QuestionDao qDao = new QuestionDao();
				Question question = qDao.retrieveQuestion(Integer.parseInt(request.getParameter("id")));
				AnswerDao aDao = new AnswerDao();
				question.setChoices(aDao.retrieveChoices(question.getQuestionId()));
				request.setAttribute("question", question);
			} catch (NumberFormatException e) {
				logger.error(e.getMessage());
				return;
			} catch (NamingException e) {
				logger.error(e.getMessage());
				return;
			} catch (SQLException e) {
				logger.error(e.getMessage());
				return;
			}
			if(request.getParameter("aid") != null){
				RequestDispatcher d = request.getRequestDispatcher("TakeExam.jsp?edit=true&aid="+request.getParameter("aid"));
				d.forward(request, response);
			} else {
				RequestDispatcher d = request.getRequestDispatcher("TakeExam.jsp?edit=true");
				d.forward(request, response);
			}
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

}
